package com.jh.netty.client;

import com.jh.netty.instruction.CommunicationPacket;
import com.jh.netty.util.ConvertCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


//自定义一个客户端业务处理类
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        // 十进制
        System.out.printf("返回的结果 [%s]%n", s);
        CommunicationPacket cp = CommunicationPacket.parse(s);
        System.out.println("cp = " + cp);
        System.out.println(cp.isValidCRC16());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

//        byte[] req;
//        ByteBuf buffer = null;
//        StringBuilder sb = new StringBuilder();
//        for (int i=0;i<100;i++){
//            sb.append("abcdefghijklmnopqrstuvwxyz");
//        }
                 // [82, 82, 1, 1, 0, -95, 6, 0, 0, 0, 2, 0, 0, 0, 5, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 52, 86, 120, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 5, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 52, 86, 120, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 5, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 52, 86, 120, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 5, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 52, 86, 120, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -121, -44]

        // 5252010100a10600000002000000051e0000000000000000000012345678050000000000000000000000000000000000000002000000051e0000000000000000000012345678050000000000000000000000000000000000000002000000051e0000000000000000000012345678050000000000000000000000000000000000000002000000051e0000000000000000000012345678050000000000000000000000000000000087d4
        String sb = "52 52 01 01 00 a1 06 00 00 00 02 00 00 00 05 1e 00 00 00 00 00 00 00 00 00 00 12 34 56 78 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 05 1e 00 00 00 00 00 00 00 00 00 00 12 34 56 78 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 05 1e 00 00 00 00 00 00 00 00 00 00 12 34 56 78 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 05 1e 00 00 00 00 00 00 00 00 00 00 12 34 56 78 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 87 d4";
        byte[] req = ConvertCode.hexString2Bytes(sb.replaceAll(" ", "")); //sb.replaceAll(" ", "").getBytes();
        ByteBuf buffer = Unpooled.buffer(req.length);
        buffer.writeBytes(req);
        ctx.writeAndFlush(buffer);
    }
}